package com.stylefeng.guns.core.base.warpper;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * 控制器查询结果的包装类基类
 *
 * @author fengshuonan
 * @date 2017年2月13日 下午10:49:36
 */
public abstract class BaseControllerWarpper {

    public Object obj = null;

    public BaseControllerWarpper(Object obj) {
        this.obj = obj;
    }

    @SuppressWarnings("unchecked")
    public Object warp() {
        if (this.obj instanceof List) {
            List<Map<String, Object>> list = (List<Map<String, Object>>) this.obj;
            for (Map<String, Object> map : list) {

                Map<String, Object> lowerMap = new HashMap<>();
                Set<String> keys = map.keySet();
                //使用H2数据库后，字段都变为大写。此处转换为小写
                keys.forEach(key -> lowerMap.put(StringUtils.lowerCase(key), map.get(key)));

                map.clear();
                map.putAll(lowerMap);

                warpTheMap(map);
            }

            return list;
        } else if (this.obj instanceof Map) {
            Map<String, Object> map = (Map<String, Object>) this.obj;
            warpTheMap(map);
            return map;
        } else {
            return this.obj;
        }
    }

    protected abstract void warpTheMap(Map<String, Object> map);
}
